package com.amitk.foldersizecalc;

import java.awt.Desktop;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.amitk.foldersizecalc.utils.FileAndFolderCalc;
import com.amitk.foldersizecalc.utils.FileAndFolderCalc.Entry;
import com.amitk.foldersizecalc.utils.impl.FileAndFolderCalcImpl;

/**
 * Main class to run this Project.
 * 
 * @author Amit kamboj
 */
public class MainClass {
	public static void main(String[] args) {
		FileAndFolderCalc calc = new FileAndFolderCalcImpl();
		List<Entry> fileAndFolderList = calc.getFileAndFolderList(args[0]);
		List<Entry> list = new ArrayList<FileAndFolderCalc.Entry>();
		converInSingleList(list, fileAndFolderList);

		if (args[1] != null && !args[1].equals("")) {
			File file = new File(args[1]);
			FileWriter fw = null;
			try {
				fw = new FileWriter(file);
				Collections.sort(list);
				for (Entry entry : list) {
					fw.write(String.format("%S\t%s\n",
							String.valueOf(entry.getSizeInMB()),
							entry.getEntryLocation()));
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					fw.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					Desktop.getDesktop().edit(file);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		} else {
			printData(list);
		}

	}

	private static void converInSingleList(List<Entry> list,
			List<Entry> fileAndFolderList) {
		if (fileAndFolderList != null && fileAndFolderList.size() > 0) {
			list.addAll(fileAndFolderList);
		}
		for (Entry entry : fileAndFolderList) {
			if (entry.getChilds() != null && entry.getChilds().size() > 0) {
				converInSingleList(list, entry.getChilds());
			}
		}
	}

	private static void printData(List<Entry> fileAndFolderList) {
		Collections.sort(fileAndFolderList);
		for (Entry entry : fileAndFolderList) {
			System.out.println(String.format("%S\t%s",
					String.valueOf(entry.getSizeInMB()),
					entry.getEntryLocation()));
		}
	}
}
